import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import '../services/directory_service.dart';
import 'photo_picker_page.dart';
import 'package:file_picker/file_picker.dart';
import '../screens/upload_tasks_screen.dart';
import '../services/file_service.dart';

class FilePickerSheet extends StatelessWidget {
  final int currentDirectoryId;
  final VoidCallback? onUploadComplete;

  const FilePickerSheet({
    Key? key,
    this.currentDirectoryId = 0,
    this.onUploadComplete,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 顶部标题栏
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '发起云添加',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
          ),
          const Divider(height: 1),

          // 上传文件部分
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '上传文件',
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildUploadOption(
                      icon: Icons.image,
                      label: '照片',
                      color: Colors.orange,
                      onTap: () {
                        Navigator.pop(context); // 关闭底部抽屉
                        Navigator.push(
                          context,
                          CupertinoPageRoute(
                            builder:
                                (context) => PhotoPickerPage(
                                  directoryId: currentDirectoryId,
                                  onUploadComplete: onUploadComplete,
                                ),
                          ),
                        );
                      },
                    ),
                    _buildUploadOption(
                      icon: Icons.videocam,
                      label: '视频',
                      color: Colors.red,
                      onTap: () {},
                    ),
                    _buildUploadOption(
                      icon: Icons.insert_drive_file,
                      label: '文档',
                      color: Colors.blue,
                      onTap: () {},
                    ),
                    _buildUploadOption(
                      icon: Icons.music_note,
                      label: '音频',
                      color: Colors.purple,
                      onTap: () {},
                    ),
                    _buildUploadOption(
                      icon: Icons.upload_file,
                      label: '文件',
                      color: Colors.blue,
                      onTap: () {
                        _pickAndUploadFile(context);
                      },
                    ),
                  ],
                ),
                const SizedBox(height: 24),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildUploadOption(
                      icon: Icons.folder,
                      label: '微信文件',
                      color: Colors.green,
                      onTap: () {},
                    ),
                    _buildUploadOption(
                      icon: Icons.smart_display,
                      label: '智能扫描',
                      color: Colors.cyan,
                      onTap: () {},
                    ),
                    _buildUploadOption(
                      icon: Icons.record_voice_over,
                      label: '录音通话',
                      color: Colors.teal,
                      onTap: () {},
                    ),
                    _buildUploadOption(
                      icon: Icons.more_horiz,
                      label: '其他文件',
                      color: Colors.grey,
                      onTap: () {},
                    ),
                  ],
                ),
              ],
            ),
          ),

          const Divider(height: 1),

          // 新建文件部分
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '新建文件',
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildNewFileOption(
                      icon: Icons.create_new_folder,
                      label: '新建文件夹',
                      onTap: () async {
                        // 弹出创建文件夹对话框
                        final shouldRefresh = await _showCreateFolderDialog(
                          context,
                        );
                        // 如果创建成功需要刷新，则关闭底部抽屉并传递刷新标志
                        if (shouldRefresh == true) {
                          Navigator.pop(context, true);
                        }
                      },
                    ),
                    _buildNewFileOption(
                      icon: Icons.note_add,
                      label: '新建任务文档',
                      onTap: () {},
                    ),
                    _buildNewFileOption(
                      icon: Icons.edit_note,
                      label: '新建笔记',
                      onTap: () {},
                    ),
                    _buildNewFileOption(
                      icon: Icons.description,
                      label: '新建Word',
                      onTap: () {},
                    ),
                  ],
                ),
              ],
            ),
          ),

          // 底部安全提示
          const Padding(
            padding: EdgeInsets.only(bottom: 16),
            child: Center(
              child: Text(
                '咕噜酱守护你的数据安全',
                style: TextStyle(fontSize: 12, color: Colors.blue),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<bool?> _showCreateFolderDialog(BuildContext context) {
    final nameController = TextEditingController();
    return showDialog<bool?>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('创建文件夹'),
          content: TextField(
            controller: nameController,
            decoration: const InputDecoration(hintText: '请输入文件夹名称'),
            autofocus: true,
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.of(context).pop(false);
              },
            ),
            TextButton(
              child: const Text('确定'),
              onPressed: () async {
                final name = nameController.text.trim();
                if (name.isEmpty) {
                  return;
                }

                try {
                  // 创建目录
                  final directoryService = DirectoryService();
                  await directoryService.createDirectory(
                    name,
                    parentId: currentDirectoryId,
                  );

                  // 通知刷新文件列表
                  if (onUploadComplete != null) {
                    onUploadComplete!();
                  } else {
                    FileService.notifyFileListUpdated();
                  }

                  Navigator.of(context).pop(true);
                } catch (e) {
                  Navigator.of(context).pop(false);
                }
              },
            ),
          ],
        );
      },
    );
  }

  Widget _buildUploadOption({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: color.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(icon, color: color),
          ),
          const SizedBox(height: 8),
          Text(label, style: const TextStyle(fontSize: 12)),
        ],
      ),
    );
  }

  Widget _buildNewFileOption({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: Colors.grey.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(icon, color: Colors.black87),
          ),
          const SizedBox(height: 8),
          Text(label, style: const TextStyle(fontSize: 12)),
        ],
      ),
    );
  }

  Future<void> _pickAndUploadFile(BuildContext context) async {
    final result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: FileType.any,
    );

    if (result != null && result.files.isNotEmpty) {
      Navigator.pop(context, true); // 关闭对话框并返回true表示需要刷新

      // 跳转到上传任务页面
      Navigator.of(context, rootNavigator: true).push(
        MaterialPageRoute(
          builder:
              (context) => UploadTasksScreen(
                onUploadComplete:
                    onUploadComplete ??
                    () {
                      // 如果没有传入回调，则使用默认的通知方式
                      FileService.notifyFileListUpdated();
                    },
              ),
        ),
      );
    }
  }
}
